import PaBaseModel from '../../core/model/PaBaseModel';

function checkConfigurationCtrl($scope, $http, ngDialog) {
  'ngInject';

  // 考核项list
  this.categoryList = [];
  // 选中的考核项
  this.activeCategory = {};
  
  // 获得扣分类型
  this.getPenaltyPointsType = (type) => {
    if (type == 1) {
      return '按分值扣分';
    } else if (type == 2) {
      return '按问题次数扣分';
    }
  };

  // 获得扣分分值
  this.getPenaltyPointsValue = (penaltyDetail) => {
    let type = penaltyDetail.kouFenType;
    let floorValue = penaltyDetail.kouFenLower;
    let ceilValue = penaltyDetail.kouFenUpper;
    if (floorValue == ceilValue) {
      return `${floorValue}分`;
    } else {
      return `${floorValue}至${ceilValue}分`;
    }
  };

  // 考核项 => viewModel
  this.handleDataToViewModel = (data) => {
    let _this = this;
    let isDefaultNodeSelected = false;
    recursionHandleData(data);

    function recursionHandleData(data) {
      let _activeCategory = null;
      data.forEach((item) => {
        item.name = item.checkCategoryName;
        item.open = false;
        item.isParent = item.leaf ? false : true;
      });
    }

  };

  // 根据数据渲染ztree
  this.renderZtree = () => {
    let _this = this;

    // click触发事件
    function zTreeOnExpand(event, treeId, treeNode) {
      $scope.$apply(() => {
        if (!treeNode.leaf && !treeNode.children) {
          $http
            .get(`${SERVER_CONTEXT}/api/criterion/getChildren/${treeNode.id}`)
            .success((data) => {
              _this.handleDataToViewModel(data);
              _this.zTreeObj.addNodes(treeNode, data);
            })
        }
      });
    }

    // click触发事件
    function zTreeOnClick(event, treeId, treeNode) {
      $scope.$apply(() => {
        if (treeNode.leaf) {
          _this.showInfo = false;
          _this.activeCategory = treeNode;
          $http
            .get(`${SERVER_CONTEXT}/api/criterion/getCriterionProject/${_this.activeCategory.id}`)
            .success((data) => {
              _this.activeCategory.safeCheckProjectList = data;
            });
        }
      });
    }
    // init jquery-Ztree
    let zTreeObj;
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    let setting = {
      callback: {
        onExpand: zTreeOnExpand,
        onClick: zTreeOnClick,
      }
    };
    // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
    let zNodes = this.categoryList;
    $(document).ready(function(){
       zTreeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
       _this.zTreeObj = zTreeObj;
       // 激活默认选中菜单
       let defaultNode = zTreeObj.getNodeByParam('isDefaultNode', true);
       zTreeObj.selectNode(defaultNode);
    });
  };
  // 初始化页面方法
  this.initCheckConfigurationView = () => {
    this.showInfo = true; // 显示提示信息
    let _this = this;
    $http
      .get(`${SERVER_CONTEXT}/api/criterion/getRoot`)
      .then((data) => {
        _this.categoryList = data.data;
        _this.handleDataToViewModel(_this.categoryList);
        _this.renderZtree();
      });
  };

  // 获得考核内容列表
  this.queryCheckStandardList = () => {
    $http
      .get(`${SERVER_CONTEXT}/api/criterion/getCriterionProject/${this.activeCategory.id}`)
      .success((data) => {
        this.activeCategory.safeCheckProjectList = data;
      });
  }

  // 编辑责任落实
  this.edit = () => {
    this.editable = true;//编辑的时候出现输入框
  };

  // 考核內容字数限制
  this.checkText = () => {
    if (this.editableCategory.checkContent && this.editableCategory.checkContent.length > '500') {
      this.reasonAddition = true;
    } else {
      this.reasonAddition = false;
    }
  }

  // 取消编辑责任落实
  this.cancelEditResponse = () => {
    this.editable = false;
    // 取消编辑 => 还原编辑model数据
    this.editableCategory.$reset();
  };

  // 保存编辑责任落实
  this.saveDutyItem = (param) => {
    // 修改表单是否提交过状态
    param.$submitted = true;

    if (this.reasonAddition) {
      return;
    }

    // 表单校验
    if (param.$invalid) {
      return false;
    }

    $http.post(`${SERVER_CONTEXT}/api/safeCheck/safe/u`, this.editableCategory).
      then((resp) => {
        console.log(resp);
      });
    this.editable = false;
    this.editableCategory.$sync();
    // this.activeCategory = new PaBaseModel(this.editableCategory);
  }  

  // 新增考核项弹窗
  this.openItemDetail = () => {
    let _this = this;
    ngDialog.open({
      template: 'dialogAssessment',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'cfgAdd',
      controller: function cfgAddCtrl($http ,$scope) {
        'ngInject';
        this.category = {
          checkCategoryID: '',
          checkProjectDescribe: '',
          kouFenType: '1',
          kouFenLower: '',
          kouFenUpper: '',
        };
        // textarea change事件
        this.checkText = () => {
          if (this.category.checkProjectDescribe && this.category.checkProjectDescribe.length > '50') {
            this.reasonAddition = true;
          } else {
            this.reasonAddition = false;
          }
        }
        this.submit = (param) => {
          // 修改表单是否提交过状态
          param.$submitted = true;

          if (this.reasonAddition) {
            return;
          }

          // 表单校验
          if (param.$invalid) {
            return false;
          }

          this.category.checkCategoryID = _this.activeCategory.id;
          let reqData = this.category;
          if (reqData.kouFenType == 2) {
            reqData.kouFenUpper = reqData.kouFenLower;
          }
          $http({
            method: 'POST',
            url: `${SERVER_CONTEXT}/api/safeCheck/safecheck/i`,
            data: reqData,
          }).then((resp) => {
            if (resp.data.success) {
              _this.queryCheckStandardList();
              layer.msg(resp.data.message);
              $scope.closeThisDialog();              
            } else {
              layer.alert(resp.data.message);
              $scope.closeThisDialog();
            }
          });
        }
      },
    });
  }

  // 编辑考核项
  this.editCheckItem = (param) => {
    let _this = this;
    ngDialog.open({
      template: 'editDialogAssessment',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'vm',
      controller: function cfgAddCtrl($http ,$scope) {
        'ngInject';
        this.category = angular.copy(param);

        // textarea change事件
        this.checkText = () => {
          if (this.category.checkProjectDescribe && this.category.checkProjectDescribe.length > '50') {
            this.reasonAddition = true;
          } else {
            this.reasonAddition = false;
          }
        }

        this.submit = (param) => {
          // 修改表单是否提交过状态
          param.$submitted = true;

          if (this.reasonAddition) {
            return;
          }

          // 表单校验
          if (param.$invalid) {
            return false;
          }

          if (this.category.kouFenType == '2') {
            this.category.kouFenUpper = this.category.kouFenLower;
          }

          this.category.checkCategoryID = _this.activeCategory.id;
          let reqData = this.category;
          $http({
            method: 'POST',
            url: `${SERVER_CONTEXT}/api/safeCheck/safecheck/u`,
            data: reqData,
          }).then((resp) => {
            if (resp.data.success) {
              layer.msg(resp.data.message);
              $scope.closeThisDialog();
              _this.queryCheckStandardList();
            } else {
              layer.alert(resp.data.message);
              $scope.closeThisDialog();
            }
          });
        }

      },
    });
  }

  // 删除考核内容
  this.deleteCheckItem = (id) => {
    let _this = this;
    $scope.modalTitle = '删除考核项';
    $scope.modalContent = '确认要删除该考核项吗?';
    ngDialog.openConfirm({
      template: 'paConfirm',
      className: 'ngdialog-theme-default pa-confirm-theme',
      scope: $scope,
    })
      .then((value) => {
          $http
            .delete(`${SERVER_CONTEXT}/api/safeCheck/safecheck/d/${id}`)
            .then((data) => {
              _this.queryCheckStandardList();
            });
        }, (reason) => {});
  }

  $scope.$watch(($scope) => {
    return $scope.checkConfiguration.activeCategory;
  }, (newVal, oldVal) => {
    this.editableCategory = new PaBaseModel(newVal);
  });

  // 初始化页面
  this.initCheckConfigurationView();
  
}

export default checkConfigurationCtrl;